<template>
  <van-popup
    v-model:show="showBottom"
    position="bottom"
    teleport="#minutesPage"
    round
    :style="{ height: '80%' }"
  >
    <div class="flex flex-col h-full justify-between">
      <div class="text-center py-4 font-bold">{{ title }}</div>
      <div v-if="loading" class="flex justify-center items-center h-full w-full gap-4">
        <van-loading></van-loading>
        加载中...
      </div>

      <div class="flex-auto overflow-y-auto pb-8" v-else>
        <template v-for="item of fieldArray" :key="item.id">
          <FormCell
            v-model:modelValue="formData[item.id]"
            :type="item.fieldType"
            :title="item.fieldName"
            :required="item.isRequired === 1"
            :placeholder="item.placeholder ? item.placeholder : '请输入内容'"
            :options="getOptions(item?.fieldOptions)"
            :maxlength="item.maxLength"
            :autocomplete="item.autocomplete && enableBusinessRule"
            :querySearchName="querySearchName"
            @onSelectSuggestions="handleSelectSuggestions"
          />
        </template>
      </div>

      <div class="px-4 py-4">
        <div
          class="bg-[#436BFF] text-white text-center h-[48px] leading-[48px] rounded-lg shadow"
          v-if="customerId"
          @click="onSave"
        >
          保存
        </div>
        <div
          class="bg-[#436BFF] text-white text-center h-[48px] leading-[48px] rounded-lg shadow"
          v-else
          @click="onCreate"
        >
          创建
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, defineProps, defineExpose, defineEmits, computed, watch } from "vue";
import FormCell from "./FormCell.vue";
import {
  createCustomerAPI,
  updateCustomerAPI,
  getCustomerTypeAPI,
  searchCompanyAPI,
} from "@/services/minutes/customer";

import { closeToast, showLoadingToast, showToast } from "vant";
import { getCustomCustomerInfoAPI } from "@/services/minutes/customer";
import { useMinutesStore } from "@/store";

const store = useMinutesStore();
const customerTypeArr = computed(() => store.customerTypeList || []);

const props = defineProps({
  customerTypeId: {
    type: String,
  },
  customerId: {
    type: String,
    required: false,
  },
  title: {
    type: String,
    default: "创建客户",
  },
});

const emits = defineEmits(["createSuccess"]);

const customerNameId = "customerName";
const salesManagerArrId = "salesManagerArr";
const sysTempArray = [
  {
    fieldName: "客户名称",
    fieldType: "String",
    isRequired: 1,
    maxLength: 20,
    minLength: 1,
    placeholder: "请输入客户用户名",
    sortOrder: 0,
    id: customerNameId,
    autocomplete: true,
  },
  {
    fieldName: "负责人",
    fieldType: "MultiSelectPeople",
    isRequired: 1,
    placeholder: "请选择负责人",
    sortOrder: 1,
    id: salesManagerArrId,
  },
];

const loading = ref(false);

const enableBusinessRule = computed(() => {
  const customerInfos =
    customerTypeArr.value.filter((v) => v.id === cp_customerTypeId.value) || [];
  console.log("enableBusinessRule 1:", customerTypeArr.value, customerInfos);

  if (customerInfos.length === 0) return false;
  console.log("enableBusinessRule:", customerTypeArr, cp_customerTypeId.value);
  console.log("enableBusinessRule2:", customerInfos[0].enableBusinessRule);
  return customerInfos[0].enableBusinessRule === 1;
});

const enableInputCustomName = computed(() => {
  return !enableBusinessRule.value;
});

// 搜索客户名称
async function querySearchName(query, cb) {
  if (query.length === 0) {
    cb([]);
    return;
  }

  const res = (await searchCompanyAPI(query)) || [];
  const { code, data, message } = res;
  if (code !== 0) {
    showToast(message);
    return;
  }
  console.log("querySearchName: ", data);
  let result = [];
  result = data.map((v) => {
    return {
      value: v.name,
    };
  });
  cb(result);
}

const customerName = ref("");

function handleSelectSuggestions(v) {
  console.log("onSelectSuggestions :>> ", v);
  customerName.value = v;
  formData.value.customerName = v;
}

// 获取表单模版 数据
async function getFormTempleData(customerTypeId) {
  loading.value = true;
  let res = await getCustomerTypeAPI(customerTypeId);
  const { code, data, message } = res;
  if (code !== 0) {
    showToast(message);
    return;
  }
  let tempArr = data;
  console.log("getCustomerTypeAPI: ", tempArr);
  tempArr.sort((a, b) => a.sortOrder - b.sortOrder);
  fieldArray.value = [...sysTempArray, ...tempArr];
  loading.value = false;
}

const editCustomerTypeId = ref("");
async function getCustomerData() {
  loading.value = true;
  const res = await getCustomCustomerInfoAPI(props.customerId);
  const { code, data, message } = res;
  if (code !== 0) {
    showToast(message);
    return;
  }
  console.log("getCustomerData: ", data);
  const {
    formData: tempFormData,
    typeId,
    salesSsoUserIds,
    salesSsoUserNames,
    name,
  } = data;
  editCustomerTypeId.value = typeId;
  const fieldValues = tempFormData?.fieldValues || [];
  await getFormTempleData(typeId);

  fieldValues.forEach((item) => {
    formData.value[item.fieldId] = item.fieldValue;
  });

  formData.value[customerNameId] = name;

  const ssoUserIdArray = salesSsoUserIds.split(",");
  const ssoUserNameArray = salesSsoUserNames.split(",");
  let salesManagerArray = ssoUserIdArray.map((v, index) => {
    return {
      id: v,
      name: ssoUserNameArray[index] || "",
    };
  });
  console.log("salesManagerArrId: ", salesManagerArray);
  formData.value[salesManagerArrId] = salesManagerArray;

  console.log("formData: ", formData.value);
  loading.value = false;
}

function getOptions(fieldOptions = "") {
  return fieldOptions.split(",").map((v) => {
    return {
      label: v,
      value: v,
    };
  });
}

const fieldArray = ref();
const formData = ref({});

watch(
  formData,
  (newValue) => {
    console.log("watch customerName: ", newValue);
    if (!enableInputCustomName.value) {
      const formDataCustomername = findValueById("customerName");
      if (formDataCustomername !== customerName.value) {
        customerName.value = "";
      }
    }
  },
  { deep: true }
);

function findValueById(id) {
  let value = formData.value[id];
  if (id === "salesManagerArr") {
    if (!value) return null;
    // 无论是否为json对象，先统一转换为json string
    value = JSON.stringify(value);
    value = JSON.parse(value);
  }
  console.log("findValueById: ", value, typeof value);
  return value;
}

const cp_customerTypeId = computed(() => {
  if (props.customerId) {
    return editCustomerTypeId.value;
  }
  return props.customerTypeId;
});

function makeParameter() {
  if (formValid()) {
    if (formValid() !== "-") {
      showToast(`${formValid()}未填写`);
    }
    return;
  }

  const name = enableInputCustomName ? findValueById("customerName") : customerName.value;
  let ssoUserIds =
    findValueById("salesManagerArr").map((value) => {
      return value.id;
    }) || [];

  ssoUserIds = Array.from(new Set(ssoUserIds));

  formData.value.customerName;
  formData.value.salesManagerArr;

  let fieldValues = [];

  Object.keys(formData.value).forEach((key) => {
    if (key === "salesManagerArr" || key === "customerName") {
      return;
    }

    let value = formData.value[key];
    if (Array.isArray(value)) {
      value = value.join(",");
    }

    const fieldConfig = fieldArray.value.find((v) => v.id === key);
    fieldValues.push({
      fieldId: fieldConfig.id,
      fieldName: fieldConfig.fieldName,
      fieldValue: value,
      order: fieldConfig.sortOrder,
      reason: "",
    });
  });

  let parameter = {
    source: 1,
    name: name,
    ssoUserIds: ssoUserIds,
    customerTypeId: cp_customerTypeId.value,
    dynamicFormData: {
      formCode: `CUSTOMER_TYPE_${cp_customerTypeId.value}`,
      fieldValues: fieldValues,
    },
  };
  console.log("onCreate parameter: ", parameter);
  return parameter;
}

async function onSave() {
  let parameter = makeParameter();

  if (!parameter) {
    return;
  }
  parameter.customerTypeId = cp_customerTypeId.value;
  showLoadingToast({
    duration: 0,
  });
  const res = await updateCustomerAPI(props.customerId, parameter);
  const { code, message } = res;
  if (code !== 0) {
    showToast(message);
    return;
  }
  closeToast();
  showToast("保存成功");
  hidden();
  emits("createSuccess");
}

async function onCreate() {
  let parameter = makeParameter();
  if (!parameter) {
    return;
  }

  showLoadingToast({
    duration: 0,
  });
  const res = await createCustomerAPI(parameter);
  const { code, message } = res;
  if (code !== 0) {
    showToast(message);
    return;
  }
  closeToast();
  showToast("创建成功");
  hidden();
  emits("createSuccess");
}

const formValid = () => {
  if (customerName.value.length === 0 && !enableInputCustomName.value) {
    showToast("请输入并【选择】客户名称");
    return "-";
  }

  for (const fieldValue of fieldArray.value) {
    const { isRequired, id, fieldName } = fieldValue;
    if (isRequired === 1) {
      let value = findValueById(id);
      if (!value) {
        console.log(`${fieldName} ${findValueById(id)} 为空 ${id} ${value}`);
        return fieldName;
      }
    }
  }
  return null;
};

// 控制显示隐藏相关
const showBottom = ref(false);

function show() {
  formData.value = {};
  fieldArray.value = [];
  showBottom.value = true;
  if (props.customerId) {
    getCustomerData();
  } else {
    getFormTempleData(props.customerTypeId);
  }
}

function hidden() {
  showBottom.value = false;
}

defineExpose({
  show,
  hidden,
});
</script>

<style scoped lang="less"></style>
